package com.zqr.lock;

import org.springframework.aop.framework.adapter.ThrowsAdviceInterceptor;

/**
 * @author zqr
 * @since 2022/11/4
 */
public class DeadLockDemo {
    public static void main(String[] args) {
        new Thread(new Lock01(Lock01.class, Lock02.class),"dead01-thread").start();
        new Thread(new Lock01(Lock02.class, Lock01.class),"dead02-thread").start();
    }

    static class Lock01 implements Runnable {
        private Object obj1;
        private Object obj2;

        public Lock01(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
        }

        @Override
        public void run() {
            synchronized (obj1) {
                while(true) {
                    System.out.println(Thread.currentThread().getName() + "获得资源1，准备获取资源2，");
                    synchronized (obj2) {
                        System.out.println(Thread.currentThread().getName() + "获得资源1，");
                        try {
                            Thread.sleep(200000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    static class Lock02 implements Runnable {
        private Object obj1;
        private Object obj2;

        public Lock02(Object obj1, Object obj2) {
            this.obj1 = obj1;
            this.obj2 = obj2;
        }

        @Override
        public void run() {
            synchronized (obj2) {
                while(true) {
                    System.out.println(Thread.currentThread().getName() + "获得资源2，准备获取资源1，");
                    synchronized (obj1) {
                        System.out.println(Thread.currentThread().getName() + "获得资源2，");
                    }
                    try {
                        Thread.sleep(200000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
